package com.atguigu.flink.chapter11;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lzc
 * @Date 2022/7/12 11:12
 */
public class Flink04_SQL_BaseUse {
    public static void main(String[] args) throws Exception {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 2L, 20),
            new WaterSensor("sensor_2", 3L, 30),
            new WaterSensor("sensor_1", 4L, 40),
            new WaterSensor("sensor_2", 5L, 50),
            new WaterSensor("sensor_1", 6L, 60)
        );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Table table = tEnv.fromDataStream(stream);
        
        // 纯sql
        
        // 1. 查询未注册的表
        //        tEnv.executeSql("sql: ddl(建表语句) 增删改");
        //tEnv.sqlQuery("sql: 查询语句");
        
       // tEnv.sqlQuery("select * from " + table +" where id='sensor_1'").execute().print();
        // 2.查询已注册的表
        tEnv.createTemporaryView("sensor", table);  // 给table对象注册临时表
        
        tEnv.sqlQuery("select * from sensor where id = 'sensor_1'").execute().print();
        
        
    }
}
